package com.shwread.android.qysw.activity;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.NewActionHelp;
import com.shwread.android.qysw.UpdateApkService;
import com.shwread.android.qysw10000136.R;
import com.shwread.android.ui.dialog.LoadingDialog;
import com.shwread.android.ui.dialog.SingleSignOnDialog;
import com.shwread.android.ui.page.BoutiquePage;
import com.shwread.android.ui.page.MainTabPage;
import com.shwread.android.ui.page.MyWorkPage;
import com.shwread.android.ui.page.NewEnterprisePage;
import com.shwread.android.ui.page.NewTrainingExamPage;
import com.shwread.android.ui.page.chat.ChatTabPage;
import com.shwread.httpsdk.http.callback.BaseAction;
import com.shwread.httpsdk.http.face.AddReadBookAction;
import com.shwread.httpsdk.http.face.DelReadBookAction;
import com.shwread.httpsdk.http.face.QryReadBookListAction;
import com.tgx.tina.android.ipc.framework.BaseActivity;

import org.geometerplus.android.util.QyreaderPerferencesUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import logic.bean.BookBean;
import logic.bean.ReadBook;
import logic.beanenum.BookStatus_Enum;
import logic.beanenum.BookType_Enum;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.dao.BookDao;
import logic.dao.UserDao;
import logic.util.AppUtils;
import logic.util.FileUtil;
import logic.util.NetworkUtil;
import logic.util.Util;
import logic.util.logutil.LogUtil;


public class BaseSimpleActivity extends BaseActivity {
    public static List<Activity> activityList = new ArrayList<Activity>();
    public static HashMap<Integer, Integer> notificationMap = new HashMap<Integer, Integer>();
    /**
     * 接收用户异常登录的广播
     */
    private LoginReceiver receiver;
    /**
     * 接收apk安装的广播
     */
    private InstallAPKReceiver apkReceiver;
    /**
     * 接收必填参数为空时的广播
     */
    private ParamsEmptyReceiver paramsEmptyReceiver;
    /**
     * 接收最近阅读数据变化的广播
     */
    private SyncReceiver syncReceiver;
    private AddNotificationReceiver notificationReceiver;

    private SingleSignOnDialog dialog;
    private LoadingDialog loadingDialog;
    private Activity currActivity;

    private BookDao bookDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        currActivity = this;
        activityList.add(this);
        LogUtil.d(DefaultConsts.TAG, "BaseSimpleActivity -->  add :" + this.getClass().getSimpleName() + ",activityList:" + activityList.size());
        bookDao = BookDao.getInstance(this);
        initReceiver();
    }

    private void initReceiver() {
        receiver = new LoginReceiver();
        registerReceiver(receiver, new IntentFilter(DefaultConsts.EXCEPTION_LOGIN_STRING));
        apkReceiver = new InstallAPKReceiver();
        registerReceiver(apkReceiver, new IntentFilter(UpdateApkService.UPDATE_APK));
        paramsEmptyReceiver = new ParamsEmptyReceiver();
        registerReceiver(paramsEmptyReceiver, new IntentFilter(DefaultConsts.PARAMS_EMPTY_STRING));
        notificationReceiver = new AddNotificationReceiver();
        registerReceiver(notificationReceiver, new IntentFilter(DefaultConsts.ADD_NOTIFICATION_ID_STRING));
        syncReceiver = new SyncReceiver();
        registerReceiver(syncReceiver, new IntentFilter(DefaultConsts.BOOKSHELF_DATA_CHANGE_BROADCAST));
    }

    private void destroyReceiver() {
        if (receiver != null) {
            unregisterReceiver(receiver);
            receiver = null;
        }
        if (apkReceiver != null) {
            unregisterReceiver(apkReceiver);
            apkReceiver = null;
        }
        if (paramsEmptyReceiver != null) {
            unregisterReceiver(paramsEmptyReceiver);
            paramsEmptyReceiver = null;
        }
        if (notificationReceiver != null) {
            unregisterReceiver(notificationReceiver);
            notificationReceiver = null;
        }
        if (syncReceiver != null) {
            unregisterReceiver(syncReceiver);
            syncReceiver = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyReceiver();
        if (loadingDialog != null) {
            loadingDialog.dismiss();
            loadingDialog = null;
        }
    }

    protected void showLoading() {
        if (null == loadingDialog) {
            loadingDialog = new LoadingDialog(this);
        }

        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!loadingDialog.isShowing()) {
                    loadingDialog.show();
                }
            }
        });
    }

    public void closeLoading() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    protected void getSyncData() {
        if (NetworkUtil.isNetAvailable(this) && Util.isNotEmpty(Const.phone_number)) {
            //从服务端同步最近阅读
            new QryReadBookListAction(this, /*bookDao.getMaxServerId(Const.phone_number)*/0L, 0, 0, new SyncListener()).start();
            commitData();
        }
    }

    private class SyncListener extends BaseAction {
        @Override
        public void OK(Object obj) {
            if (null == obj) {
                return;
            }
            List<ReadBook> data = (List<ReadBook>) obj;
                bookDao.syncBooks(data);
//            if (null != data && !data.isEmpty() && data.size() > 0) {
//            }
        }
    }

    private class SyncReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Util.isEmpty(Const.phone_number)) {
                return;
            }
            final String packageName = intent.getStringExtra("packageName");
            if (Util.isNotEmpty(packageName) && packageName.equals(AppUtils.getPackageName(context))) {
                final int flag = intent.getIntExtra("flag", -1);
                System.err.println("--<Sync>--接收到数据变更的广播，flag:" + flag);
                switch (flag) {
                    case DefaultConsts.UPDATE_NO_SYNC:
                        if (NetworkUtil.isNetAvailable(BaseSimpleActivity.this)) {
                            commitData();
                        }
                        break;
                    case DefaultConsts.DELETE:
                        BookBean bean = (BookBean) intent.getSerializableExtra("BookBean");
                        if (null != bean) {
                            delData(bean);
                        }
                        break;
                    case DefaultConsts.UPDATE_SYNC://将本地数据同步到服务端
                        Log.e("11111111", "同步数据到服务器");
                        if (NetworkUtil.isNetAvailable(BaseSimpleActivity.this)) {
                            List<BookBean> data = bookDao.getSyncBooks(Const.phone_number);
                            for (int i = 0; i < data.size(); i++) {
                                boolean isLast = i == (data.size() - 1);
                                BookBean bookBean = data.get(i);
                                if (bookBean.book_id <= 0
                                        || bookBean.startTime == 0
                                        || bookBean.endTime == 0
                                        || bookBean.isOnline == BookBean.ONLINE && (bookBean.server_chapterid == 0
                                        || Util.isEmpty(bookBean.chapterName))) {
                                    continue;
                                }
                                if (bookBean.status == BookStatus_Enum.DOWNLOAD.getValue() && bookBean.isOnline == BookBean.ONLINE) {
                                    bookBean.isOnline = BookBean.NO_ONLINE;
                                }
                                new AddReadBookAction(currActivity,
                                        bookBean.book_id,
                                        bookBean.isOnline,
                                        bookBean.startTime,
                                        bookBean.endTime,
                                        "2",
                                        bookBean.server_chapterid,
                                        bookBean.chapterName,
                                        new addReadBookListener(bookBean, isLast)).start();
                                try {
                                    Thread.sleep(1000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        break;
                }
            }
        }
    }

    /**
     * 同步数据
     */
    private void commitData() {
        List<BookBean> data = bookDao.getSyncBooks(Const.phone_number);
        //		System.err.println("--<Sync>--未同步数据:"+data.size()+","+data.toString());
        for (int i = 0; i < data.size(); i++) {
            boolean isLast = i == (data.size() - 1);
            final BookBean bean = data.get(i);
            if (bean.book_id <= 0 || bean.startTime == 0 || bean.endTime == 0) {
                continue;
            }
            if (bean.isOnline == BookBean.ONLINE && (bean.server_chapterid == 0 || Util.isEmpty(bean.chapterName))) {
                continue;
            }
            //	        System.err.println("--<Sync>--正在同步数据:"+i+","+bean.toString());
            if (bean.syncStatus == BookBean.NO_SYNC) { //未同步的数据进行提交
                if (bean.status == BookStatus_Enum.DOWNLOAD.getValue() && bean.isOnline == BookBean.ONLINE) {
                    bean.isOnline = BookBean.NO_ONLINE;
                }
                new AddReadBookAction(this, bean.book_id, bean.isOnline, bean.startTime, bean.endTime, "2", bean.server_chapterid, bean.chapterName, new addReadBookListener(bean, isLast)).start();
            } else if (bean.syncStatus == BookBean.DELETE) {//删除状态的数据进行删除
                new DelReadBookAction(this, bean.book_id, new DelReadBookListener(bean)).start();
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void delData(BookBean bean) {
        if (bean.server_id == 0) {
            return;
        }
        if (NetworkUtil.isNetAvailable(BaseSimpleActivity.this)) {
            //			System.err.println("--<Sync>--删除数据:"+bean.toString());
            //如果有serverId，调用删除最近阅读接口
            new DelReadBookAction(this, bean.book_id, new DelReadBookListener(bean)).start();
        }
    }

    private class DelReadBookListener extends BaseAction {
        BookBean bookBean;

        public DelReadBookListener(BookBean bookBean) {
            this.bookBean = bookBean;
        }

        @Override
        public void OK(Object obj) {
            //			System.err.println("--<Sync>--删除数据:"+bookBean);
            bookDao.delReadingBook(bookBean);
        }
    }

    private class addReadBookListener extends BaseAction {
        BookBean bookBean;
        boolean isLast;

        public addReadBookListener(BookBean bookBean, boolean isLast) {
            this.bookBean = bookBean;
            this.isLast = isLast;
        }

        @Override
        public void OK(Object obj) {
            //			System.err.println("--<Sync>--添加数据:"+bookBean);
            bookBean.syncStatus = BookBean.SYNC;
            bookDao.updateSyncBook(bookBean);
        }
    }

    private class LoginReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context arg0, Intent arg1) {
            final String json = arg1.getStringExtra("json");
            final String packageName = arg1.getStringExtra("packageName");
            if (Util.isNotEmpty(packageName)
                    && packageName.equals(AppUtils.getPackageName(arg0))
                    && Util.isNotEmpty(json)
                    && !(currActivity instanceof NewLoginActivity)////登录界面屏蔽抢登
                    && ! BookShelfActivity.OFFINE_READ) {//离线阅读状态下屏蔽抢登
                //测试地址的白名单帐号屏蔽抢登提示框
                if (!UserDao.getInstance(BaseSimpleActivity.this).getLastLoginUser().getAccount().equals("18989898989")) {
                    LogUtil.e(DefaultConsts.TAG, "接收到广播：帐号在别处登录，" + json);
                    if (null == dialog) dialog = new SingleSignOnDialog(arg0);
                    dialog.setJson(arg1.getStringExtra("json"));
                    dialog.setCancelable(false);
                    if (!dialog.isShowing()) dialog.show();
                }
            }
        }
    }

    /**
     * 安装apk监听
     */
    private class InstallAPKReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context arg0, Intent arg1) {
            final String packageName = arg1.getStringExtra("packageName");
            if (Util.isNotEmpty(packageName) && packageName.equals(AppUtils.getPackageName(arg0))) {
                LogUtil.d(DefaultConsts.TAG, "接收到广播：APK下载完成");
                final String filePath = arg1.getStringExtra(UpdateApkService.UPDATE_APK_FILE);
                installAPK(filePath);
            }
        }
    }

    private class ParamsEmptyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context arg0, Intent arg1) {
            final String packageName = arg1.getStringExtra("packageName");
            if (Util.isNotEmpty(packageName) && packageName.equals(AppUtils.getPackageName(arg0)) && !(currActivity instanceof NewLoginActivity)) {
                LogUtil.e(DefaultConsts.TAG, "接收到广播：必填参数为空");
                exit();
                startActivity(new Intent(BaseSimpleActivity.this, NewLoginActivity.class));
            }
        }
    }

    private class AddNotificationReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context arg0, Intent arg1) {
            final String packageName = arg1.getStringExtra("packageName");
            if (Util.isNotEmpty(packageName) && packageName.equals(AppUtils.getPackageName(arg0))) {
                final int id = arg1.getIntExtra(DefaultConsts.NOTIFICATION_ID, 0);
                LogUtil.d(DefaultConsts.TAG, "接收到广播：发出通知栏消息，notificationId:" + id);
                notificationMap.put(id, DefaultConsts.MESSAGE_NOTIFICATION_FLAG);
                //记录最后一次推送的消息id
                final long msgId = arg1.getIntExtra(DefaultConsts.LAST_PUSH_MESSAGE_ID, 0);
                QyreaderPerferencesUtil.getInstance(BaseSimpleActivity.this, Const.phone_number).setLastPushMessageId(msgId);
            }
        }
    }

    /**
     * 安装APK
     */
    protected void installAPK(String apkPath) {
        if (Util.isNotEmpty(apkPath) && FileUtil.exists(apkPath)) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(new File(apkPath)), "application/vnd.android.package-archive");
            startActivity(intent);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * 检查MainActivity是否启动
     *
     * @return
     */
    public static boolean existMainActivity() {
        for (Activity activity : activityList) {
            if (activity instanceof MainActivity) return true;
        }
        return false;
    }

    public static void gotoMainActivity() {
        for (Activity activity : activityList) {
            if (!(activity instanceof MainActivity)) activity.finish();
        }
    }

    public static void exit() {
        if (existMainActivity()) MainTabPage.clearPage();
        for (Activity activity : activityList) {
            LogUtil.e(DefaultConsts.TAG, "BaseSimpleActivity -->" + activity.getClass().getSimpleName() + " -- finish!!");
            activity.finish();
        }
        activityList.clear();
        notificationMap.clear();
        Const.clear();
        BoutiquePage.destroy();
        NewEnterprisePage.destroy();
        //NewsPage.destroy();
        NewTrainingExamPage.destroy();
        //OrderIndexPage.destroy();
        MyWorkPage.destroy();
        //MyHealthyPage.destroy();
        ChatTabPage.destroy();
        NewActionHelp.setDefaultLoginKey();
    }

    /**
     * 清除通知栏的通知
     *
     * @param context
     * @param flag    -1：全部，0：消息推送，1：下载
     */
    public static void clearNotification(Context context, int flag) {
        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        for (Integer id : notificationMap.keySet()) {
            switch (flag) {
                case -1:
                    manager.cancel(id);
                    break;
                default:
                    if (notificationMap.get(id) == flag) {
                        manager.cancel(id);
                        notificationMap.remove(id);
                    }
                    break;
            }
        }
        if (flag == -1) {
            notificationMap.clear();
        }
    }

    protected void setBookTypeIcon(ImageView img, String type) {
        if (TextUtils.isEmpty(type)) return;
        if (type.equals(BookType_Enum.LISTEN)) {
            img.setVisibility(View.VISIBLE);
            img.setBackgroundResource(R.drawable.listen_icon);
        } else {
            img.setVisibility(View.GONE);
        }
    }
}
